package com.xkcyy.one.ai.common.tool;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkcyy.one.ai.common.tool.util.ToolDefinitionGenerator;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractSimpleTool<TArguments extends ToolArguments> implements Tool {
    protected final ObjectMapper objectMapper = new ObjectMapper();
    private final ToolDefinition definition;

    public AbstractSimpleTool() {
        this.definition = ToolDefinitionGenerator.generate(getClass());
        this.definition.getFunction().setName(this.getName());
        this.definition.getFunction().setDescription(this.getDescription());
    }

    @Override
    public ToolDefinition getDefinition() {
        return definition;
    }

    @Override
    public String execute(String jsonInputParams) {
        try {
            // 1. 序列化为 TArguments
            TArguments arguments = objectMapper.readValue(jsonInputParams, getArgumentsClass());
            // 2. 调用 doExecute
            return doExecute(arguments);
        } catch (Exception e) {
            log.error("Failed to execute tool", e);
            throw new RuntimeException("Failed to execute tool: " + e.getMessage(), e);
        }
    }

    public abstract String doExecute(TArguments arguments);

    @Override
    public String getType() {
        return "function";
    }

    /**
     * 获取参数类型
     */
    @SuppressWarnings("unchecked")
    private Class<TArguments> getArgumentsClass() {
        return (Class<TArguments>) ((java.lang.reflect.ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

}
